/*
 *    Copyright 2021 Institute of Software Chinese Academy of Sciences, ISRC

 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

import router from '@system.router';
import http from '@ohos.net.http';
import fileio from '@ohos.fileio'
import featureAbility from '@ohos.ability.featureAbility'
import bundle from '@ohos.bundle'
import zlib from '@ohos.zlib'
import file from '@system.file'
import prompt from '@system.prompt';
import util from '@ohos.util'
export const FILE_CONTENT = 'hello world';
export function randomString(num) {
    let len= num;
    var $chars = 'aaaabbbbcccc';
    var maxPos = $chars.length;
    var pwd = '';
    for (var i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}
export function fileToReadOnly(fpath) {
    try {
        let fd = fileio.openSync(fpath, 0o1)
        fileio.fchmodSync(fd, 0o444)
        fileio.fsyncSync(fd)
        fileio.closeSync(fd)
        return true
    }
    catch (e) {
        console.log('fileio Failed to fileToReadOnly for ' + e);
        return false
    }
}

export async function fileName(testName) {
    let context = featureAbility.getContext();
    console.log('myapp fileName' + context);
    let data = await context.getFilesDir();
    console.log('myapp fileName' + data);
    let BASE_PATH = data + '/';
    console.log('myapp fileName' + BASE_PATH);
    return BASE_PATH + testName + '_' + randomString(testName.length);
}
export async function dirName() {
    let context = featureAbility.getContext();
    console.log('myapp dirName' + context);
    let data = await context.getFilesDir();
    console.log('myapp dirName' + data);
    let BASE_PATH = data + '/';
    console.log('myapp dirName' + BASE_PATH);
    return BASE_PATH;
}
export function prepareFile(fpath, content) {
    try {
        let fd = fileio.openSync(fpath, 0o102, 0o666)
        fileio.ftruncateSync(fd)
        fileio.writeSync(fd, content)
        fileio.fsyncSync(fd)
        fileio.closeSync(fd)
        return true
    }
    catch (e) {
        console.log('Failed to prepareFile for ' + e)
        return false
    }
}
export async function unzip_file(zipFile, bundlename, _this) {
    var zipDest = zipFile;
    let unzipdir = await dirName();
    var options = {};

    zlib.unzipFile(zipDest, unzipdir, options).then((data) => {
        console.info("myapp unzip data:" + data);
        console.info("myapp unzip data2:" + unzipdir);
        console.info("myapp unzip data2:" + zipDest);
        let dir = fileio.opendirSync(unzipdir);
        fileio.unlink(zipDest).then(function() {
            console.info("myapp rm succeed");
        }).catch(function(err){
            console.info("myapp rm failed with error:"+ err);
        });
        for(let i = 0;i < 6; i++) {
            dir.read().then(function (dirent){
                console.info("fileIo read successfully:"+ dirent.name);
                if (dirent.name.substring(dirent.name.length - 4, dirent.name.length) == '.hap') {
                    let path = unzipdir + '/' + dirent.name;
                    console.info("fileIo read successfully:"+ path);
                    install(path, _this);
                }
            }).catch(function(err){
                console.info("fileIO_read failed with error:"+ err);
            });
        }

    }).catch((err) => {
        console.log("myapp unzip err:" + err);
        return false;
    })
}
export async function install(path, _this){
    let installer = await bundle.getBundleInstaller();
    installer.install([path],{
        userId: 100,
        installFlag: 0,
        isKeepData: false
    }, (err, data) => {
        console.log('myapp install err.code finish<======='
        + err.code);
        console.log('myapp install data.status finish<======='
        + data.status);
        console.log('myapp install data.statusMessage finish<======='
        + data.statusMessage);
        if (err.code == -1) {
            prompt.showToast({
                message: "安装失败"
            })
            _this.downloadText = "安装";
        } else {
            prompt.showToast({
                message: "安装成功"
            })
            _this.downloadText = "更新";
        }
    })
}
export default {
    data: {
        accessToken: "",
        descTabInfo: ['应用详情', '评论'],
        percent: 0,
        isPaused: true,
        intervalId : null,
        downloadText : "安装",
        pic: "",
        inputValue: '',
        starScore: '',
        xtoken: "",
        xsession: "",
        xaccessToken: "",
        commentList: [],
        appList: [],
        commentContent: "",
        commentId: [],
        score: [],
        averageScore: "",
        userID: ""
    },
    onInit() {
        console.info("myapp this.appItem.shortdesc:" + this.appItem.shortDesc);
        let bundleFlags = 8;
        let userId = 100;
        bundle.getAllApplicationInfo(bundleFlags, userId, (err, data) => {
            if (err) {
                console.error('myapp getAllApplicationInfo Operation failed. Cause: ' + JSON.stringify(err));
                return;
            }
            //console.info('myapp getAllApplicationInfo Operation successful. Data:' + JSON.stringify(data));
            for (var i = 0; i < data.length; i++) {
                //console.info("myapp bundle name:" + data[i].name);
                if (this.appItem.shortDesc == data[i].name) {
                    this.downloadText = "更新";
                    break;
                }
            }
        })
        //because guest can get comment,so should get temporary_xtoken&&accesstoken firstly
        this.get_temporary_xtoken();
        console.info("myapp this.downloadText:" + this.downloadText);

    },
    onReady() {
        this.onDownloadIcon();
    },
    onDestroy() {

    },
    get_access_token(){
        let url = this.$app.$def.data.usermgmtIP + '/v1/accesstoken';
        let httpRequest = http.createHttp();
        httpRequest.on('headersReceive', (data) => {
            //console.info('myapp get_access_token header: ' + data.header);
        });
        let session_value = 'AUTHSERVERSESSIONID=' + this.$app.$def.data.session + ';';
        let cookie_value = session_value + 'XSRF-TOKEN=' + this.$app.$def.data.token + ';';
        console.info("myapp get_access_token cookie:" + cookie_value);
        httpRequest.request(
            url,
            {
                method: 'POST', // 可选，默认为“GET”
                header: {
                    'Content-Type': 'application/json',
                    'Cookie': cookie_value,
                    'Connection': 'keep-alive',
                    'Accept-Encoding': 'gzip, deflate, br',
                    'Accept': '*/*',
                    'X-XSRF-TOKEN': this.$app.$def.data.token
                },
                extraData:
                {
                    "userFlag": this.$app.$def.data.name,
                    "password": this.$app.$def.data.password
                },
                connectTimeout: 60000, // 可选，默认为60s
                readTimeout: 60000, // 可选，默认为60s
            },(err, data) => {
            if (!err) {
                console.info('myapp get_access_token Result:' + data.result);
                console.info('myapp get_access_token code:' + data.responseCode);
                console.info('myapp get_access_token cookies:' + data.cookies);
                this.accessToken = JSON.parse(data.result).accessToken;
                console.info("myapp get_access_token accesstoken:" + this.accessToken);
                this.download();
                httpRequest.destroy();
            } else {
                console.info('myapp get_access_token error:' + err);
                httpRequest.destroy();
            }
        }
        );
    },

    get_temporary_access_token() {
        let url = this.$app.$def.data.usermgmtIP + '/v1/accesstoken';
        let httpRequest = http.createHttp();
        httpRequest.on('headersReceive', (data) => {
            //console.info('myapp get_temporary_access_token header: ' + data.header);
        });
        let session_value = 'AUTHSERVERSESSIONID=' + this.xsession + ';';
        let cookie_value = session_value + 'XSRF-TOKEN=' + this.xtoken + ';';
        console.info("myapp get_temporary_access_token cookie:" + cookie_value);
        httpRequest.request(
            url,
            {
                method: 'POST', // 可选，默认为“GET”
                header: {
                    'Content-Type': 'application/json',
                    'Cookie': cookie_value,
                    'Connection': 'keep-alive',
                    'Accept-Encoding': 'gzip, deflate, br',
                    'Accept': '*/*',
                    'X-XSRF-TOKEN': this.xtoken
                },
                extraData:
                {
                    "userFlag": 'guest',
                    "password": 'guest'
                },
                connectTimeout: 60000, // 可选，默认为60s
                readTimeout: 60000, // 可选，默认为60s
            },(err, data) => {
            if (!err) {
                console.info('myapp get_temporary_access_token code:' + data.responseCode);
                console.info('myapp get_temporary_access_token cookies:' + data.cookies);
                this.xaccessToken = JSON.parse(data.result).accessToken;
                console.info("myapp xaccesstoken:" + this.xaccessToken);
                this.onGetComment();
                httpRequest.destroy();
            } else {
                console.info('myapp get_temporary_access_token error:' + err);
                httpRequest.destroy();
            }
        }
        );

    },
    async create_fileIo (dataresult, pkgName) {
        let fpath =await fileName(pkgName);
        fpath = fpath + '.zip';
        console.log('myapp fileio_test_fchmod_async path:' + fpath);
        let ret = prepareFile(fpath, FILE_CONTENT);
        console.log('myapp fileio_test_fchmod_async prepare result' + ret);
        let ss = fileio.createStreamSync(fpath, 'w+');
        console.log('myapp fileio_test_fchmod_async create stream:' + ss);
        let wlen = ss.writeSync(dataresult);
        console.log('myapp fileio_test_fchmod_async write len:' + wlen);
        ss.closeSync();

        await unzip_file(fpath, pkgName, this);

    },

    download() {
        this.downloadText = "正在安装";
        // 每一个httpRequest对应一个http请求任务，不可复用
        let httpRequest = http.createHttp();
        // 用于订阅http响应头，此接口会比request请求先返回。可以根据业务需要订阅此消息
        // 从API 8开始，使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
        httpRequest.on('headersReceive', (data) => {
            //console.info('header: ' + data.header);
        });
        console.info("myapp download begin");
        console.info("myapp appItem appid:" + this.appItem.appId + ",packageid:" + this.appItem.packageId);
        var downloadUrl = this.$app.$def.data.appstoreIP + "/mec/appstore/v1/apps/" + this.appItem.appId + "/packages/" + this.appItem.packageId + "/action/download";
        console.info("myapp download url:" + downloadUrl);
        httpRequest.request(
            // 填写http请求的url地址，可以带参数也可以不带参数。URL地址需要开发者自定义。GET请求的参数可以在extraData中指定
            downloadUrl,
            {
                method: 'GET', // 可选，默认为“GET”
                // 开发者根据自身业务需要添加header字段
                header: {
                    'Content-Type': 'application/json',
                    'X-XSRF-TOKEN': this.$app.$def.data.token,
                    'accesstoken': this.accessToken
                },
                // 当使用POST请求时此字段用于传递内容
                extraData: {
                    //"data": "data to send",
                },
                connectTimeout: 60000, // 可选，默认为60s
                readTimeout: 60000, // 可选，默认为60s
            },(err, data) => {
            if (!err) {
                // data.result为http响应内容，可根据业务需要进行解析
                console.info('myapp download code:' + data.responseCode);
                console.info('myapp Result:' + data.result);
                this.create_fileIo(data.result, this.appItem.name);
            } else {
                console.info('myapp download error:' + err);
                // 当该请求使用完毕时，调用destroy方法主动销毁。
                httpRequest.destroy();
            }
        }
        );
    },
    onInstallClick() {
        if (this.$app.$def.data.name != "guest") {
            this.get_access_token();
        } else {
            prompt.showToast({
                message: "请先进行用户注册/登录"
            })
        }
    },
    onUser() {
        console.info("myapp page to user");
        if (this.$app.$def.data.name == "guest") {
            router.push({
                uri: "pages/login/login",
                params: {
                    lastPage: "pages/description/description",
                    appItem: this.appItem
                }
            });
        } else {
            router.push({
                uri: "pages/userstate/userstate",
            });
        }
    },
    onIcon() {
        let url = this.pic;
        this.$refs.canvas.clear();
        const el =this.$refs.canvas;
        var ctx =el.getContext('2d');
        ctx.clearRect(0, 0, 60, 60);
        var img = new Image();
        img.src = url;
        console.log('myapp img.src:',img.src);
        img.onload = function() {
            console.log('myapp begin to draw image');
            ctx.drawImage(img, 0, 0, 60, 60);
            url = null;
        };
        img.onerror = function() {
            console.log('myapp onload fail');
        };
    },
    onDownloadIcon() {
        // 每一个httpRequest对应一个http请求任务，不可复用

        let httpRequest = http.createHttp();
        // 用于订阅http响应头，此接口会比request请求先返回。可以根据业务需要订阅此消息
        // 从API 8开始，使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
        httpRequest.on('headersReceive', (data) => {
            console.info('header: ' + data.header);
        });
        let url = this.$app.$def.data.appstoreIP + "/mec/appstore/v1/packages/" + this.appItem.packageId + "/action/download-icon"
        httpRequest.request(
            // 填写http请求的url地址，可以带参数也可以不带参数。URL地址需要开发者自定义。GET请求的参数可以在extraData中指定
            url,
            {
                method: 'GET', // 可选，默认为“GET”
                // 开发者根据自身业务需要添加header字段
                header: {
                    'Content-Type': 'application/json'
                },
                // 当使用POST请求时此字段用于传递内容

                extraData: {
                    //"data": "data to send",
                },
                connectTimeout: 60000, // 可选，默认为60s
                readTimeout: 60000, // 可选，默认为60s
            },(err, data) => {
            if (!err) {
                // data.result为http响应内容，可根据业务需要进行解析
                //console.info('myapp Result:' + data.result);
                console.info('myapp onDownloadIcon:' + data.responseCode);
                // data.header为http响应头，可根据业务需要进行解析
                var lresult = new Uint8Array(data.result);
                var that = new util.Base64();
                var finresult = that.encodeToStringSync(lresult);
                this.pic = "data:image/jpeg;base64," + finresult;
                console.info("myapp pic:" + this.pic);
                this.onIcon();
            } else {
                console.info('myapp error:' + err);
                // 当该请求使用完毕时，调用destroy方法主动销毁。
                httpRequest.destroy();
            }
        }
        );

    },
    get_comment_token(){
        if (this.$app.$def.data.name == "guest" || this.$app.$def.data.userId == '') {
            prompt.showToast({
                message: "guest用户不允许评论，请先进行用户注册/登录"
            });
        }

        let url = this.$app.$def.data.usermgmtIP + '/v1/accesstoken';
        let httpRequest = http.createHttp();
        httpRequest.on('headersReceive', (data) => {
        });

        let session_value = 'AUTHSERVERSESSIONID=' + this.$app.$def.data.session + ';';
        let token_value = 'XSRF-TOKEN=' + this.$app.$def.data.token+ ';';
        let cookie_value = session_value + token_value;
        console.info("myapp get_comment_token cookie:" + cookie_value);
        httpRequest.request(
            url,
            {
                method: 'POST', // 可选，默认为“GET”
                header: {
                    'Content-Type': 'application/json',
                    'Cookie': cookie_value,
                    'Connection': 'keep-alive',
                    'Accept-Encoding': 'gzip, deflate, br',
                    'Accept': '*/*',
                    'X-XSRF-TOKEN': this.$app.$def.data.token
                },
                extraData:
                {
                    "userFlag": this.$app.$def.data.name,
                    "password": this.$app.$def.data.password
                },
                connectTimeout: 60000, // 可选，默认为60s
                readTimeout: 60000, // 可选，默认为60s
            },(err, data) => {
            if (!err) {
                console.info('myapp get_comment_token code:' + data.responseCode);
                console.info('myapp get_comment_token cookies:' + data.cookies);
                this.accessToken = JSON.parse(data.result).accessToken;
                console.info("myapp get_comment_token accesstoken:" + this.accessToken);
                console.info("myapp get_comment_token token:" + this.$app.$def.data.token);
                console.info("myapp get_comment_token session:" + this.$app.$def.data.session);
                httpRequest.destroy();
                this.onSubmitComment();
            } else {
                console.info('myapp get_comment_token error:' + err);
                httpRequest.destroy();
            }
        }
        );
    },
    onCommentContent(e) {
         this.inputValue = e.text;
         console.info("myapp onSubmitComment:" + this.inputValue);
    },
    onCommentStar(e) {
        if (isNaN(e.text)) {
            prompt.showToast({
                message: "评分必须为数字"
            })
            return
        }
        if (parseInt(e.text) < 1 || parseInt(e.text) > 5) {
            prompt.showToast({
                message: "评分范围为1-5"
            })
            return
        }
        this.starScore = e.text;
        console.info("myapp onSubmitComment:" + this.starScore);
    },
    onSubmitComment() {
        if (this.inputValue == '' || this.starScore == '') {
            prompt.showToast({
                message: "请按要求输入评论内容和评分"
            })
        } else {
            if (this.$app.$def.data.name == "guest" || this.$app.$def.data.userId == '') {
                prompt.showToast({
                    message: "guest用户不允许评论，请先进行用户注册/登录"
                })
            } else {
                console.info("myapp onSubmiturl:" + this.$app.$def.data.userId);
                let url = this.$app.$def.data.appstoreIP + '/mec/appstore/v1/apps/' + this.appItem.appId +
                '/comments?userId=' + this.$app.$def.data.userId + "&userName=" + this.$app.$def.data.name;
                let session_value = 'AUTHSERVERSESSIONID=' + this.$app.$def.data.session + ';';
                let cookie_value = session_value + 'XSRF-TOKEN=' + this.$app.$def.data.token + ';';
                let httpRequest = http.createHttp();
                httpRequest.on('headersReceive', (data) => {
                    //console.info('myapp onSubmitComment header: ' + data.header);
                });
                httpRequest.request(
                    url,
                    {
                        method: 'POST', // 可选，默认为“GET”
                        header: {
                            'Content-Type': 'application/json',
                            'Connection': 'keep-alive',
                            'Accept-Encoding': 'gzip, deflate, br',
                            'Accept': '*/*',
                            'Cookie': cookie_value,
                            'X-XSRF-TOKEN': this.$app.$def.data.token,
                            'accesstoken': this.accessToken
                        },
                        extraData:
                        {
                            "body": this.inputValue,
                            "score": this.starScore
                        },
                        connectTimeout: 60000, // 可选，默认为60s
                        readTimeout: 60000, // 可选，默认为60s
                    }, (err, data) => {
                    if (!err) {
                        console.info('myapp onSubmitComment code:' + data.responseCode);
                        console.info('myapp onSubmitComment result:' + data.result);
                        prompt.showToast({
                            message: data.result
                        })
                        this.inputValue = '';
                        this.starScore = '';
                        this.onGetComment();
                        httpRequest.destroy();
                    } else {
                        console.info('myapp onSubmitComment error:' + err);
                        prompt.showToast({
                            message: err
                        })
                        httpRequest.destroy();
                    }
                }
                );
            }
        }
    },

    get_temporary_xtoken() {
        let url  = this.$app.$def.data.usermgmtIP + '/v1/identity/verifycode-image?t=' + Math.random()
        let httpRequest = http.createHttp();
        httpRequest.on('napi_headersReceive', (data) => {
        });
        httpRequest.request(
            url,
            {
                method: 'GET', // 可选，默认为“GET”
                header: {
                    'Content-Type': 'image/jpeg',
                },
                connectTimeout: 60000, // 可选，默认为60s
                readTimeout: 60000, // 可选，默认为60s
            },(err, data) => {
            if (!err) {
                console.info('myapp:' + data.result);
                console.info('myapp:' + JSON.stringify(data.cookies));
                this.xtoken = data.cookies.substring(data.cookies.length-130, data.cookies.length-94);
                this.xsession = data.cookies.substring(data.cookies.length-32);
                console.info('myapp:' + this.xtoken);
                console.info('myapp:' + this.xsession);
                this.get_temporary_access_token();
            } else {
                console.info('myapp:' + err);
                // 当该请求使用完毕时，调用destroy方法主动销毁。
                httpRequest.destroy();
            }
        }
        );
    },
    onGetComment() {
        console.info('myapp onGetComment xaccessToken:' + this.xaccessToken);
        let httpRequest = http.createHttp();
        // 用于订阅http响应头，此接口会比request请求先返回。可以根据业务需要订阅此消息
        // 从API 8开始，使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
        httpRequest.on('headersReceive', (data) => {
            console.info('header: ' + data.header);
        });
        let url = this.$app.$def.data.appstoreIP + "/mec/appstore/v2/apps/" + this.appItem.appId + "/comments?limit=100&offset=0";
        console.info('myappurl: ' + url);
        httpRequest.request(
            url,
            {
                method: 'GET', // 可选，默认为“GET”
                // 开发者根据自身业务需要添加header字段
                header: {
                    'Content-Type': 'application/json',
                    'accesstoken': this.xaccessToken
                },
                // 当使用POST请求时此字段用于传递内容
                extraData: {
                    //"data": "data to send",
                },
                connectTimeout: 60000, // 可选，默认为60s
                readTimeout: 60000, // 可选，默认为60s
            },(err, data) => {
            if (!err) {
                // data.result为http响应内容，可根据业务需要进行解析
                console.info('myapp Result:' + data.result);
                console.info('myapp code2:' + data.responseCode);
                // data.header为http响应头，可根据业务需要进行解析
                var comment_obj = JSON.parse(data.result);
                if (comment_obj.total == 0) {
                    this.commentList = JSON.stringify([{"user":{"userName":""},"body":"暂无用户评论","score":''}])
                    this.appList = JSON.parse(this.commentList);
                } else {
                    this.commentList = JSON.stringify(comment_obj.results)
                    this.appList = JSON.parse(this.commentList);
                    var score = 0;
                    console.log("myapp score:", this.appItem.atpTestTaskId)
                    //this.averageScore = this.appItem.atpTestTaskId;
                    this.onAppScore(this.appItem.appId);
                }     
            } else {
                console.info('myapp error:' + err);
                // 当该请求使用完毕时，调用destroy方法主动销毁。
                httpRequest.destroy();
            }
        }
        );
    },
    onAppScore(appId) {
        console.info("myapp onDownloadIcon");
        // 每一个httpRequest对应一个http请求任务，不可复用
        let httpRequest = http.createHttp();
        // 用于订阅http响应头，此接口会比request请求先返回。可以根据业务需要订阅此消息
        // 从API 8开始，使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
        httpRequest.on('headersReceive', (data) => {
            console.info('header: ' + data.header);
        });
        let url = this.$app.$def.data.appstoreIP + "/mec/appstore/v1/apps/" + appId
        httpRequest.request(
        // 填写http请求的url地址，可以带参数也可以不带参数。URL地址需要开发者自定义。GET请求的参数可以在extraData中指定
            url,
            {
                method: 'GET', // 可选，默认为“GET”
                // 开发者根据自身业务需要添加header字段
                header: {
                    'Content-Type': 'application/json',
                    'accesstoken': this.xaccessToken
                },
                // 当使用POST请求时此字段用于传递内容
                extraData: {
                    //"data": "data to send",
                },
                connectTimeout: 60000, // 可选，默认为60s
                readTimeout: 60000, // 可选，默认为60s
            },(err, data) => {
            if (!err) {
                // data.header为http响应头，可根据业务需要进行解析
                this.averageScore = JSON.parse(data.result).score;
            } else {
                console.info('myapp error:' + err);
                // 当该请求使用完毕时，调用destroy方法主动销毁。
                httpRequest.destroy();
            }
        }
        );
    }

};